package sd.czw.com.mmgapp.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.yanzhenjie.recyclerview.swipe.Closeable;
import com.yanzhenjie.recyclerview.swipe.OnSwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import com.zhy.http.okhttp.OkHttpUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import sd.czw.com.mmgapp.Contants;
import sd.czw.com.mmgapp.R;
import sd.czw.com.mmgapp.adapter.ShopCartAdapter;
import sd.czw.com.mmgapp.customviews.ListViewDecoration;
import sd.czw.com.mmgapp.model.loginandsign.LoginNormalCallback;
import sd.czw.com.mmgapp.model.loginandsign.LoginNormalModel;
import sd.czw.com.mmgapp.model.shopcart.ShopCartCallback;
import sd.czw.com.mmgapp.model.shopcart.ShopCartModel;
import sd.czw.com.mmgapp.utils.SpUtils;

/**
 * Created by czw
 * desc 描述：
 * on 2017/7/5.
 */
public class ShoppingCartFragment extends Fragment {

    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.smrv)
    SwipeMenuRecyclerView mMenuRecyclerView;
    @Bind(R.id.check_box)
    CheckBox checkBox;
    @Bind(R.id.tv_sum)
    TextView tvSum;
    @Bind(R.id.btn_js)
    Button btnJs;
    private View views;
    private String token;
    private String username;
    private List<ShopCartModel.ErrmsgBean.GoodsListBean> mdatas = new ArrayList<>();
    private ShopCartAdapter shopcartAdapter;
    private int page = 0;
    private int start = 0;
    private int limit = 6;
    private String rec_type = "0";
    private String check_rec_type;
    private int count = 0;
    private int totalNumber = 0;
    private float total_Price = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        views = inflater.inflate(R.layout.fragment_shopcart, container, false);
        ButterKnife.bind(this, views);

        token = SpUtils.setToken(getContext()).getString("token", "");
        username = SpUtils.setUsername(getContext()).getString("username", "");
        // rlBack.setVisibility(View.VISIBLE);
        getdata();
        mMenuRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));// 布局管理器。
        mMenuRecyclerView.addItemDecoration(new ListViewDecoration());// 添加分割线。
//        mMenuRecyclerView.setHasFixedSize(true);
//        mMenuRecyclerView.setNestedScrollingEnabled(false);
        // 设置菜单创建器。
        mMenuRecyclerView.setSwipeMenuCreator(swipeMenuCreator);
        // 设置菜单Item点击监听。
        mMenuRecyclerView.setSwipeMenuItemClickListener(menuItemClickListener);
        shopcartAdapter = new ShopCartAdapter(getContext(), mdatas);
//        //menuAdapter.setOnItemClickListener(onItemClickListener);
//        //mMenuRecyclerView.addOnScrollListener(mOnScrollListener);
        mMenuRecyclerView.setAdapter(shopcartAdapter);
        //runOnUiThread();

        return views;
    }


    /**
     * 网络请求数据
     *
     */
    private void getdata() {
        OkHttpUtils.post().url("http://miemiegou.com/wap/app_flow.php")
                .addParams("username",username)
                .addParams("token",token).addParams("time", Contants.Time).addParams("sign",Contants.Sign)
                .build().execute(new ShopCartCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(ShopCartModel response, int id) {
                if (response.getErrcode() == 1){
                    if (response.getErrmsg().getGoods_list() != null){
                        List<ShopCartModel.ErrmsgBean.GoodsListBean> goods_list = response.getErrmsg().getGoods_list();
                        mdatas.addAll(goods_list);
                        shopcartAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    @OnClick({R.id.rl_back,R.id.btn_js})
    void onclick(View view){
        switch (view.getId()){
            //结算
            case R.id.btn_js:

                break;
        }
    }

    /**
     * 菜单创建器。在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int width = getResources().getDimensionPixelSize(R.dimen.y180);
            // MATCH_PARENT 自适应高度，保持和内容一样高；也可以指定菜单具体高度，也可以用WRAP_CONTENT。
            int height = ViewGroup.LayoutParams.MATCH_PARENT;

            // 添加右侧的删除按钮
            {
                SwipeMenuItem addItem = new SwipeMenuItem(getContext())
                        .setBackgroundDrawable(R.drawable.selector_red)// 点击的背景。
                        .setText("删除")
                        .setTextColor(ContextCompat.getColor(getContext(),R.color.white))
                        .setTextSize(16)
                        .setWidth(width) // 宽度。
                        .setHeight(height); // 高度。
                swipeRightMenu.addMenuItem(addItem); // 添加一个按钮到右侧菜单。
            }
        }
    };

    /**
     * 菜单点击监听。
     */
    private OnSwipeMenuItemClickListener menuItemClickListener = new OnSwipeMenuItemClickListener() {
        @Override
        public void onItemClick(Closeable closeable, final int adapterPosition, int menuPosition, int direction) {
            closeable.smoothCloseMenu();// 关闭被点击的菜单。
            if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
                OkHttpUtils.post().url("http://miemiegou.com/wap/app_flow.php").addParams("username", username)
                        .addParams("token", token).addParams("time", Contants.Time)
                        .addParams("sign", Contants.Sign).addParams("step", "drop_goods")
                        .addParams("id", mdatas.get(adapterPosition).getRec_id()).build()
                        .execute(new LoginNormalCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {

                            }

                            @Override
                            public void onResponse(LoginNormalModel response, int id) {
                                if (response.getErrcode() == 1) {
                                    /**
                                     * 移除item
                                     */
                                    mdatas.remove(adapterPosition);
                                    shopcartAdapter.notifyItemRemoved(adapterPosition);
                                } else {
                                    Toast.makeText(getContext(), "" + response.getErrmsg(), Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
            }
        }
    };
//
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


}
